package com.zhida.jiyangcenter.utils

import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.manager.app
import chooongg.base.utils.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.mian.BaseActivity

object NavigationUtils {

    data class NavigationAppItem(val name: String, val type: String, val longitude: Double, val latetude: Double, val destination: String? = null)

    const val AUTONAVI_PACKAGENAME = "com.autonavi.minimap"// 高德地图APP包名
    const val BAIDUMAP_PACKAGENAME = "com.baidu.BaiduMap"// 百度地图APP包名
    const val TENCENTMAP_PACKAGENAME = "com.tencent.map"// 腾讯地图APP包名

    fun startNavigationToOutApp(context: BaseActivity, longitude: Double, latetude: Double, destination: String? = null) {
        val isInstallAutoNavi = isInstallApp(AUTONAVI_PACKAGENAME)
        val isInstallBaiDu = isInstallApp(BAIDUMAP_PACKAGENAME)
        val isInstallTencent = isInstallApp(TENCENTMAP_PACKAGENAME)

        val datas = ArrayList<NavigationAppItem>().apply {
            if (isInstallAutoNavi) add(NavigationAppItem("高德地图", AUTONAVI_PACKAGENAME, longitude, latetude, destination))
            if (isInstallBaiDu) add(NavigationAppItem("百度地图", BAIDUMAP_PACKAGENAME, longitude, latetude, destination))
            if (isInstallTencent) add(NavigationAppItem("腾讯地图", TENCENTMAP_PACKAGENAME, longitude, latetude, destination))
        }
        NavigationSelectBottomDialog().setDatas(datas).show(context.supportFragmentManager, "NavigationDialog")
    }

    class NavigationSelectBottomDialog : BottomSheetDialogFragment() {

        private lateinit var recyclerView: RecyclerView
        private val adapter = Adapter()
        private var datas: ArrayList<NavigationAppItem> = ArrayList()

        override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
            val dialog = BottomSheetDialog(context ?: app.activityTop)
            recyclerView = RecyclerView(context ?: app.activityTop)
            recyclerView.setBackgroundColor(app.resColor(R.color.colorContent))
            recyclerView.layoutParams = ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT)
            recyclerView.layoutManager = LinearLayoutManager(context ?: app.activityTop)
            recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER
            recyclerView.adapter = adapter
            recyclerView.setPadding(0, dp2px(16f), 0, dp2px(24f))
            val headerView = FrameLayout(context ?: app.activityTop).apply {
                this.addView(View(context ?: app.activityTop).apply {
                    setBackgroundResource(R.color.colorBackgroundDark)
                    layoutParams = FrameLayout.LayoutParams(dp2px(120f), app.resDimenOffset(R.dimen.dividerSmall)).apply {
                        this.gravity = Gravity.CENTER
                    }
                })
                this.addView(TextView(context ?: app.activityTop).apply {
                    text = "选择导航App到目的地"
                    setPadding(dp2px(8f), dp2px(8f), dp2px(8f), dp2px(8f))
                    setTextColor(app.resColor(R.color.textGray))
                    setBackgroundResource(R.color.colorContent)
                    layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        this.gravity = Gravity.CENTER
                    }
                })
                layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
                    this.bottomMargin = dp2px(16f)
                }
            }
            adapter.addHeaderView(headerView)
            if (datas.isEmpty()) {
                adapter.addHeaderView(TextView(context).apply {
                    layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                    val margin = resDimenSize(R.dimen.marginContent)
                    setPadding(margin, margin, margin, margin)
                    gravity = Gravity.CENTER
                    text = "检测到系统中没有支持的地图App\n请安装以下任意地图App\n高德地图、百度地图、腾讯地图"
                    setTextColor(resColor(R.color.textNormal))
                })
            } else {
                adapter.setNewData(datas)
            }
            adapter.addFooterView(View(context).apply {
                layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, resDimenSize(R.dimen.marginContent))
            })
            dialog.setContentView(recyclerView)
            adapter.setOnItemClickListener { _, _, position ->
                dialog.dismiss()
                val item = datas[position]
                when (item.type) {
                    AUTONAVI_PACKAGENAME -> {
                        startActivity(Intent(Intent.ACTION_VIEW).apply {
                            setPackage("com.autonavi.minimap")
                            addCategory(Intent.CATEGORY_DEFAULT)
                            data = Uri.parse(StringBuilder("amapuri://route/plan/").apply {
                                append("?sourceApplication=${requireContext().resString(R.string.app_name)}")
                                if (item.destination != null) append("&dname=${item.destination}")
                                append("&dlon=${item.longitude}")
                                append("&dlat=${item.latetude}")
                                append("&dev=0")
                                append("&t=0")
                            }.toString())
                        })
                    }
                    BAIDUMAP_PACKAGENAME -> {
                        startActivity(Intent().apply {
                            data = Uri.parse(StringBuilder("baidumap://map/navi").apply {
                                append("?coord_type=gcj02")
                                append("&location=${item.latetude},${item.longitude}")
                                if (item.destination != null) append("|name=${item.destination}")
                                append("&mode=driving")
                            }.toString())
                        })
                    }
                    TENCENTMAP_PACKAGENAME -> {
                        startActivity(Intent().apply {
                            data = Uri.parse(StringBuilder("qqmap://map/routeplan").apply {
                                append("?type=drive")
                                append("&fromcoord=CurrentLocation")
                                if (item.destination != null) append("&to=${item.destination}")
                                append("&tocoord=${item.latetude},${item.longitude}")
                                append("&referer=ATFBZ-EQ3KD-OZ24G-PE3CI-4IAO5-RPF53")
                            }.toString())
                        })
                    }
                }
            }
            return dialog
        }

        fun setDatas(datas: ArrayList<NavigationAppItem>): NavigationSelectBottomDialog {
            this.datas = datas
            return this
        }

        private class Adapter : BaseQuickAdapter<NavigationAppItem, BaseViewHolder>(R.layout.dialog_item_navigation) {
            override fun convert(helper: BaseViewHolder, item: NavigationAppItem) {
                helper.setText(R.id.tv_title, item.name)
            }
        }
    }
}